package cn.brilliantfuture.commentry.service;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import cn.brilliantfuture.commentry.exception.ParamErrorException;
import cn.brilliantfuture.commentry.safe.VerifyMessageLocal;
import cn.brilliantfuture.commentry.util.MD5;

/**
 * 
 * Title: Communication Entry
 * 
 * Author: LiTian
 * 
 * Date: 2012-3-26
 * 
 * Description:
 * 
 */
public abstract class AbstractTransactionService {
	
	protected static final Logger logger = Logger.getLogger(AbstractTransactionService.class);

	public static final String JSON_DATA_FORMAT = "json";

	public static final String XML_DATA_FORMAT = "xml";
	
	public static final List<String> PROTOCOL_VERSONS = Arrays.asList("1.0", "1.2", "2.0");

	/**
	 * 参数调用错误
	 */
	public static final String PARAM_ERROR = "PARAM_ERROR";

	/**
	 * 数据格式错误
	 */
	public static final String DATA_FORMAT_ERROR = "DATA_FORMAT_ERROR";

	/**
	 * 调用失败
	 */
	public static final String INVOKE_FAILURE = "INVOKE_FAILURE";

	/**
	 * 调用成功
	 */
	public static final String INVOKE_SUCCESS = "INVOKE_SUCCESS";

	/**
	 * 根据条件没有找到相关数据
	 */
	public static final String NULL_DATA = "NULL_DATA";

	/**
	 * 支付成功
	 */
	public static final String PAYMENT_SUCCESS = "PAYMENT_SUCCESS";

	/**
	 * 支付失败
	 */
	public static final String PAYMENT_FAILURE = "PAYMENT_FAILURE";
	
	/**
	 * 退款成功
	 */
	public static final String REFUND_SUCCESS = "REFUND_SUCCESS";

	/**
	 * 退款失败
	 */
	public static final String REFUND_FAILURE = "REFUND_FAILURE";
	
	/**
	 * 余额不足
	 */
	public static final String SCANT_BALANCE = "SCANT_BALANCE";
	
	/**
	 * 重复提交
	 */
	public static final String DUPLICATE_SUBMIT = "DUPLICATE_SUBMIT";
	
	/**
	 * 方法不存在
	 */
	public static final String METHOD_NONEXIST = "METHOD_NONEXIST";
	
	protected InitialContext context;
	
	/**
	 * 相关参数验证
	 * 
	 * @param appKey
	 *            为其分配的KEY
	 * @param appCode
	 *            为其分配的CODE
	 * @param version
	 *            当前协议版本
	 * @param timestamp
	 *            时间戳
	 * @param format
	 *            数据格式
	 * @param method 方法名称
	 * @param data 相关参数数据
	 * @param sign MD5签名
	 * @throws ParamErrorException 
	 */
	protected void validParam2DOT0(String appKey, String appCode, String version, String timestamp, String format, String method, String data, String sign) throws ParamErrorException {
		boolean isApp = false;
		boolean isVersion = false;
		boolean isTimestamp = true;
		boolean isFormat = false;
		boolean isSign = false;

		StringBuffer sb = new StringBuffer();
		sb.append("app_key=").append(appKey);
		sb.append("&app_code=").append(appCode);
		sb.append("&v=").append(version);
		sb.append("&timestamp=").append(timestamp);

		if (null != appKey && null != appCode){
			isApp = true;
		}else{
			isApp = false;
		}
		
		if (null != version && PROTOCOL_VERSONS.contains(version) && "2.0".equals(version)){
			isVersion = true;
		} else {
			isVersion = false;
		}

		if (null != format){
			if (!format.equals(JSON_DATA_FORMAT) && !format.equals(XML_DATA_FORMAT)){
				isFormat = false;
			}else{
				isFormat = true;
				sb.append("&format=").append(format);
			}
		}else{
			isFormat = true;
		}
		
		sb.append("&method=").append(method);
		sb.append("&data=").append(data);
		
		logger.info("SIGN -> " + sign + " MD5 -> " + MD5.getMD5(sb.toString()));
		
		if (sign.equals(MD5.getMD5(sb.toString()))){
			isSign = true;
		}

		if (!isApp || !isVersion || !isTimestamp || !isFormat || !isSign)
			throw new ParamErrorException();
	}

	/**
	 * 相关参数验证
	 * 
	 * @param appKey
	 *            为其分配的KEY
	 * @param appCode
	 *            为其分配的CODE
	 * @param version
	 *            当前协议版本
	 * @param timestamp
	 *            时间戳
	 * @param format
	 *            数据格式
	 */
	protected void validParam(String appKey, String appCode, String version, String timestamp, String format) throws ParamErrorException{
		
		logger.info("appKey -> " + appKey + " appCode -> " + appCode + " version -> " + version + " timestamp -> " + timestamp + " format -> " + format);
		
		boolean isApp = false;
		boolean isVersion = true;
		boolean isTimestamp = true;
		boolean isFormat = false;

		if (null != appKey && null != appCode){
			isApp = true;
		}else{
			isApp = false;
		}

		if (null != format){
			if (!format.equals(JSON_DATA_FORMAT) && !format.equals(XML_DATA_FORMAT)){
				isFormat = false;
			}else{
				isFormat = true;
			}
		}else{
			isFormat = true;
		}

		if (!isApp || !isVersion || !isTimestamp || !isFormat)
			throw new ParamErrorException();
	}
	
	/**
	 * 验证APP是否存在
	 * @param appKey 为其分配的KEY
	 * @param appCode 为其分配的CODE
	 * @return Integer
	 */
	protected Integer validAppParam(String appKey, String appCode) throws ParamErrorException, NamingException{

		VerifyMessageLocal verifyMessageLocal = (VerifyMessageLocal) context.lookup("commentry-ear/VerifyMessageImpl/local");

		Integer groupId = verifyMessageLocal.validAppParam(appKey, appCode);
		
		if (null == groupId)
			throw new ParamErrorException();
		
		return groupId;
	}

	/**
	 * 初始化访问环境
	 */
	public void init() {
		Properties properties = new Properties();
		properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		properties.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		
		//properties.put(Context.PROVIDER_URL, "localhost");
		// HA-JNDI is registered under the partition name passed to JBoss via -g 
		String partitionName = System.getProperty("jboss.partition.name", "cabinetServer");
		properties.put("jnp.partitionName", partitionName);
		
		try {
			context = new InitialContext(properties);
		} catch (NamingException e) {
			logger.error("Init content fail\n", e);
		}
	}
	
	
}
